package com.lewis.anf.servlet;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import com.lewis.anf.AnfDownloadThread;
import com.lewis.anf.pojo.AnfBaseItem;
import com.lewis.anf.pojo.AnfCat;
import com.lewis.anf.pojo.AnfCategory;
import com.lewis.anf.pojo.AnfUrlsPair;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.annotations.Annotations;
import com.thoughtworks.xstream.io.xml.DomDriver;

public class AnfProcess extends HttpServlet{

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		
		String values = req.getParameter("value");
		PrintWriter out = res.getWriter();
		if (values == ""){
			out.println("<html><head><title>" +
	                "Bye!</title></head>");
	    out.println("<body><h1>"+ "Bye bye"+ "</h1></body></html>");
		}
		
		//parse the ids;
		String[] ids = values.split(";");
		List<String> idList = Arrays.asList(ids);
		//convert xml to pojo
		File file = new File(getServletContext().getRealPath("/")+ "/anfdata.xml");
		XStream xstream = new XStream(new DomDriver());
        Annotations.configureAliases(xstream, AnfCat.class);
        Annotations.configureAliases(xstream, AnfCategory.class);
        Annotations.configureAliases(xstream, AnfBaseItem.class);
        Annotations.configureAliases(xstream, AnfUrlsPair.class);
		AnfCat cats = (AnfCat) xstream.fromXML(new FileInputStream(file));
		
		//generate html and return
		AnfCat newCats = new AnfCat();
		for (AnfCategory anfC:cats.getList()){
			AnfCategory newCat = null;
			List<AnfBaseItem> newList = new ArrayList<AnfBaseItem>();
			for(AnfBaseItem anfB: anfC.getItems()){
				if (idList.contains(anfB.getProdId())){
					newList.add(anfB);
				}
			}
			if (!newList.isEmpty()){
				newCat = new AnfCategory();
				newCat.setItems(newList);
				newCat.setName(anfC.getName());
				newCats.getList().add(newCat);
			}
			
		}
		
		XStream newXstream = new XStream(new DomDriver());
        Annotations.configureAliases(newXstream, AnfCat.class);
        Annotations.configureAliases(newXstream, AnfCategory.class);
        Annotations.configureAliases(newXstream, AnfBaseItem.class);
        Annotations.configureAliases(newXstream, AnfUrlsPair.class);
        String xml = newXstream.toXML(newCats);
		
        DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
		  try
		  {
		   InputStream inputStream = new ByteArrayInputStream(xml.getBytes());
		   DocumentBuilder db=dbf.newDocumentBuilder();
		   Document doc=db.parse(inputStream);
		   DOMSource source=new DOMSource(doc);
		   StreamResult result=new StreamResult(res.getWriter());
		   InputStream is = getClass().getResourceAsStream("../anfResult.xsl");
		            StreamSource ss=new StreamSource(is);
		            TransformerFactory tff = TransformerFactory.newInstance();
		            Transformer tf = tff.newTransformer(ss);
		            tf.setOutputProperty("encoding", "utf-8");
		            tf.transform(source, result);
		  }
		        catch(ParserConfigurationException e){e.printStackTrace();}
		        catch(SAXException e){e.printStackTrace();}
		        catch(IOException e){e.printStackTrace();}
		        catch(TransformerConfigurationException e){e.printStackTrace();}
		        catch(TransformerException e){e.printStackTrace();}
        
		out.flush();
		//verify and download picture
		AnfDownloadThread anfD = new AnfDownloadThread(newCats);
		anfD.start();
		
	    System.out.println("jiba");
		
	}
	
	

}
